package com.example.stock.ui.scan;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.example.stock.R;
import com.example.stock.base.BaseActivity;
import com.example.stock.databinding.ActivityAutoQueryBinding;
import com.example.stock.model.GoodsData;
import com.example.stock.model.GoodsOrderBean;
import com.example.stock.util.DBUtil;
import com.example.stock.util.DialogUtils;
import com.example.stock.util.Utils;

import java.io.Serializable;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.lifecycle.Observer;
import per.goweii.actionbarex.common.OnActionBarChildClickListener;

public class AutoQueryActivity extends BaseActivity<ActivityAutoQueryBinding, AutoQueryViewModel> {

    private String mCode = "";

    private GoodsOrderBean orderBean;

    public static void start(Context context, GoodsOrderBean bean) {
        Intent intent = new Intent(context, AutoQueryActivity.class);
        intent.putExtra("BEAN", (Serializable) bean);
        context.startActivity(intent);
    }

    @Override
    protected Class<AutoQueryViewModel> initViewModel() {
        return AutoQueryViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_auto_query;
    }

    @Override
    protected void initView() {
        orderBean = (GoodsOrderBean) getIntent().getSerializableExtra("BEAN");
        mBinding.abc.setOnLeftIconClickListener(new OnActionBarChildClickListener() {
            @Override
            public void onClick(View v) {
                showFinishDialog();
            }
        });
        mBinding.abc.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AutoQueryEditActivity.startEdit(AutoQueryActivity.this, orderBean);
                finish();
            }
        });
        mBinding.tvName.setText(String.format("单号：%s", orderBean.getDjh()));
        initData(true);
        initScanner(true);
        mBinding.layoutAuto.setVisibility(View.VISIBLE);
        mBinding.button.setVisibility(View.GONE);
        setViewEnabled();

//        mBinding.etCode.setText("0403100126|方体袋|160*160*500*0.25|个|200|20211103|2021/11/03|昆山普清净化科技有限公司");
    }

    private void initData(boolean isInit) {
        mBinding.tvItem1.setText(orderBean.getDjh());
        if (isInit || TextUtils.isEmpty(mCode)) {
            mBinding.tvItem2.setText("");
            mBinding.tvItem3.setText("");
            mBinding.tvItem4.setText("");
            mBinding.tvItem5.setText("");
            mBinding.tvItem6.setText("");
            mBinding.tvItem7.setText("");
            mBinding.tvItem8.setText("");
            mBinding.tvItem9.setText(orderBean.getGysName());
        } else {
            String[] all = mCode.split("\\|");
            mBinding.tvItem2.setText(all[0]);
            mBinding.tvItem3.setText(all[1]);
            mBinding.tvItem4.setText(all[2]);
            mBinding.tvItem5.setText(all[3]);
            mBinding.tvItem6.setText(all[4]);
            mBinding.tvItem7.setText(all[5]);
            mBinding.tvItem8.setText(all[6]);
            mBinding.tvItem9.setText(all[7]);
        }
        mBinding.etCode.setText("");
        mBinding.etCode.setFocusable(true);
        mBinding.etCode.setFocusableInTouchMode(true);
        mBinding.etCode.requestFocus();
    }

    private void setViewEnabled(){
        int childCount = mBinding.itemInputLayout.getChildCount();
        for (int i = 0; i < childCount; i++) {
            mBinding.itemInputLayout.getChildAt(i).setClickable(false);
            mBinding.itemInputLayout.getChildAt(i).setEnabled(false);
        }
    }

    private void showFinishDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("确定退出本次盘点吗？");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.show();
    }

    @Override
    protected void registerObserve() {
        super.registerObserve();
        mViewModel.mBean.observe(this, new Observer<GoodsData>() {
            @Override
            public void onChanged(GoodsData inventoryBean) {
                mBinding.etCode.setText("");
                mBinding.etCode.setFocusable(true);
                mBinding.etCode.setFocusableInTouchMode(true);
                mBinding.etCode.requestFocus();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromInputMethod(mBinding.etCode.getWindowToken(), 0);
                if (inventoryBean != null) {
                    /*if (inventoryBean.getType() > 0) {
                        DialogUtils.showInfoDialog(AutoQueryActivity.this, "该物料已添加入库，是否重复添加？", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                DialogUtils.closeInfoDialog();
                                extracted(inventoryBean);
                            }
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                DialogUtils.closeInfoDialog();
                            }
                        });
                        return;
                    }*/
                    extracted(inventoryBean);
                } else {
                    Utils.getInstance().showToast("查询无次信息");
                    resetStartActivity();
                }
            }
        });
    }

    private void extracted(GoodsData inventoryBean) {
        inventoryBean.setType(1);
        String hgsl = inventoryBean.getHgsl(); // 合格数量
        String sl = inventoryBean.getSl(); // 入库数量
        double hgslLong = TextUtils.isEmpty(hgsl) ? 0L : Double.parseDouble(hgsl);
        double slLong = TextUtils.isEmpty(sl) ? 0L : Double.parseDouble(sl);
        boolean isV = slLong > hgslLong;
        if (isV) {
            DialogUtils.showInfoDialog(AutoQueryActivity.this, "入库数量大于合格数据，是否保存？", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    DialogUtils.closeInfoDialog();
                    DBUtil.getInstance().update(inventoryBean);
                    Utils.getInstance().showToast("更新物料成功");
                    initData(false);
                    resetStartActivity();
                }
            }, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    DialogUtils.closeInfoDialog();
                    mBinding.etCode.setText("");
                    mBinding.etCode.setFocusable(true);
                    mBinding.etCode.setFocusableInTouchMode(true);
                    mBinding.etCode.requestFocus();
                    resetStartActivity();
                }
            });
        } else {
            DBUtil.getInstance().update(inventoryBean);
            Utils.getInstance().showToast("更新物料成功");
            initData(false);
            resetStartActivity();
        }
    }

    private void initScanner(boolean addList) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mBinding.etCode, 0);
        mBinding.etCode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    String code = mBinding.etCode.getText().toString();
                    if (TextUtils.isEmpty(code)) {
                        mBinding.etCode.setFocusable(true);
                        mBinding.etCode.setFocusableInTouchMode(true);
                        mBinding.etCode.requestFocus();
                        return false;
                    }
                    addOrScan(code);
                }
                return false;
            }
        });
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (TextUtils.isEmpty(s.toString())) {
                    imm.hideSoftInputFromWindow(mBinding.etCode.getWindowToken(), 0);
                } else {
                    imm.showSoftInputFromInputMethod(mBinding.etCode.getWindowToken(), 0);
                    mBinding.etCode.setSelection(s.toString().length() - 1);
                }
            }
        };
        mBinding.etCode.removeTextChangedListener(textWatcher);
        if (addList) {
            mBinding.etCode.addTextChangedListener(textWatcher);
        }
        mBinding.etCode.setText("");
        mBinding.etCode.setFocusable(true);
        mBinding.etCode.setFocusableInTouchMode(true);
        mBinding.etCode.requestFocus();
        mBinding.setItemBean(new GoodsData());
    }

    public void addOrScan(String res) {
        mCode = res;
        // 二维码信息格式：0存货编码，1存货名称，2规格型号，3计量单位，4数量，5批次号，6生产日期，7供应商名称
        if (!TextUtils.isEmpty(res)) {
            String[] all = res.split("\\|");
            try {
                if(all.length <= 7 || TextUtils.isEmpty(all[7])){
                    showDialog("扫码格式错误：" + res);
                    return;
                }
                if (TextUtils.equals(orderBean.getBillType(), "23") && !TextUtils.equals(orderBean.getGysName(), all[7])) {
                    showDialog("供应商不一致，不是该到货单物料，请重新扫描 " + orderBean.getGysName() + ": " + all[7]);
                    return;
                }
                GoodsData scanData = new GoodsData();
                scanData.setDjh(orderBean.getDjh());
                scanData.setInvcode(all[0]);
                scanData.setInvname(all[1]);
                scanData.setInvspec(all[2]);
                scanData.setSl(all[4]);
                scanData.setPcCode(all[5]);
                scanData.setRkrq(all[6]);
                scanData.setGysName(all[7]);
                mViewModel.query(orderBean, scanData);
            } catch (Exception e) {
                showDialog("二维码扫描解析异常，请联系管理员 e : " + e.getMessage());
            }
        } else {
            showDialog("扫描数据为空");
        }
    }

    public void onScanClick(View view) {
        if (TextUtils.isEmpty(mBinding.tvItem1.getText().toString())) {
            Utils.getInstance().showToast(mBinding.tvItem1.getHint().toString());
            return;
        }
        /*if (isEmpty(mBinding.tvItem2)) {
            return;
        }
        if (isEmpty(mBinding.tvItem3)) {
            return;
        }
        if (isEmpty(mBinding.tvItem4)) {
            return;
        }
        if (isEmpty(mBinding.tvItem5)) {
            return;
        }*/
        if (isEmpty(mBinding.tvItem6)) {
            return;
        }
        if (isEmpty(mBinding.tvItem7)) {
            return;
        }
        /*if (isEmpty(mBinding.tvItem8)) {
            return;
        }*/
        // 二维码信息格式：0存货编码，1存货名称，2规格型号，3计量单位，4数量，5批次号，6生产日期，7供应商名称
        if (TextUtils.isEmpty(mBinding.tvItem9.getText().toString())) {
            Utils.getInstance().showToast(mBinding.tvItem9.getHint().toString());
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append(getEditStr(mBinding.tvItem2)).append("|");
        sb.append(getEditStr(mBinding.tvItem3)).append("|");
        sb.append(getEditStr(mBinding.tvItem4)).append("|");
        sb.append(getEditStr(mBinding.tvItem5)).append("|");
        sb.append(getEditStr(mBinding.tvItem6)).append("|");
        sb.append(getEditStr(mBinding.tvItem7)).append("|");
        sb.append(getEditStr(mBinding.tvItem8)).append("|");
        sb.append(getEditStr(mBinding.tvItem9));
        Log.d("wyj", "res : " + sb.toString());
        addOrScan(sb.toString());
    }

    private boolean isEmpty(AppCompatTextView text) {
        if (TextUtils.isEmpty(text.getText().toString())) {
            Utils.getInstance().showToast(text.getHint().toString());
            return true;
        }
        return false;
    }

    private String getEditStr(AppCompatEditText editText){
        Editable text = editText.getText();
        if(text != null){
            return text.toString().trim();
        }
        return "";
    }

    private String getEditStr(AppCompatTextView editText){
        CharSequence text = editText.getText();
        if(!TextUtils.isEmpty(text)){
            return text.toString().trim();
        }
        return "";
    }

    private void showDialog(String msg) {
        DialogUtils.showInfoDialog(this, msg, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                DialogUtils.closeInfoDialog();
                mCode = "";
                mBinding.etCode.setText(mCode);
                mBinding.etCode.setFocusable(true);
                mBinding.etCode.setFocusableInTouchMode(true);
                mBinding.etCode.requestFocus();
                resetStartActivity();
            }
        });
    }

    @Override
    public void onBackPressed() {
        showFinishDialog();
    }


    private void resetStartActivity(){
        AutoQueryActivity.start(this, orderBean);
        finish();
    }
}
